<template>
  <div>
    <a-form ref="formRef" :model="formState" :rules="rules" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
      <a-form-item label="多账号分配" name="distribute_mode">
        <ButtonGroup
          :modelValue="formState.distribute_mode"
          @update:modelValue="handleDistributeModeChange"
          :values="[1, 2, 3, 4]"
          :isMutex="true"
          :labels="['多账号一致', '不同定向包', '不同标题包', '不同素材组']"
        />
      </a-form-item>
      <a-form-item label="创建方式" name="add_mode">
        <a-radio-group v-model:value="formState.add_mode">
          <a-radio-button :value="1">新建计划</a-radio-button>
          <a-radio-button :value="2" :disabled="isExistingPlanDisabled">已有计划</a-radio-button>
        </a-radio-group>
      </a-form-item>

      <!-- 已有计划选择区域 -->
      <template v-if="formState.add_mode === 2">
        <a-form-item label="已有计划">
          <div style="display: flex; align-items: center">
            <span v-if="selectedPlans.length > 0" style="margin-right: 12px"> 已选择: {{ selectedPlans.length }}个计划 </span>
            <a-button type="primary" @click="openSelectCampaignModal">选择广告计划</a-button>
          </div>
        </a-form-item>

        <!-- 简化的已选计划展示区域 -->
        <a-form-item v-if="selectedPlans.length > 0" label="已选计划">
          <div class="selected-plans-simple">
            <div class="account-group" v-for="account in accountsWithPlans" :key="account._id">
              <div class="account-header">
                <span class="account-name">{{ account.Name }}</span>
                <span class="account-count">{{ getAccountSelectedCount(account._id) }}个计划</span>
              </div>
              <div class="plan-chips">
                <a-tag
                  v-for="plan in getAccountPlans(account._id)"
                  :key="plan.id"
                  closable
                  @close="removePlan(plan.id)"
                  class="plan-chip"
                >
                  {{ plan.name }} (ID: {{ plan.id }})
                </a-tag>
              </div>
            </div>
          </div>
        </a-form-item>
      </template>

      <!-- 以下字段仅在新建计划时显示 -->
      <template v-if="formState.add_mode === 1">
        <a-form-item label="投放范围" name="campaignType">
          <a-radio-group v-model:value="formState.campaignType">
            <a-radio-button :value="1">商店</a-radio-button>
            <a-radio-button :value="2">非商店</a-radio-button>
            <a-radio-button :value="3">米盟</a-radio-button>
          </a-radio-group>
        </a-form-item>

        <a-form-item v-if="formState.campaignType === 2 || formState.campaignType === 3" label="投放方式" name="deliveryPolicy">
          <a-radio-group v-model:value="formState.deliveryPolicy">
            <a-radio-button :value="0">加速投放</a-radio-button>
            <a-radio-button :value="1">匀速投放</a-radio-button>
          </a-radio-group>
        </a-form-item>

        <a-form-item label="流量优选" name="trafficMode">
          <a-checkbox
            :checked="!!formState.trafficMode"
            @change="(e: Event) => formState.trafficMode = (e.target as HTMLInputElement).checked ? 1 : 0"
          >
            开启流量优选
          </a-checkbox>
        </a-form-item>

        <a-form-item label="计划名称" name="name">
          <CampaignName 
            v-model:name="formState.name" 
            v-model:auto_suffix_id="formState.auto_suffix_id"
            :maxLength="10"
          />
        </a-form-item>

        <a-form-item label="预算" name="budget">
          <a-input-number
            v-model:value="formState.budget"
            :min="200"
            :max="100000000"
            :precision="0"
            addon-after="元/天"
            style="width: 200px"
            @change="(value: number | null) => (formState.budget = String(value))"
          />
        </a-form-item>

        <!-- 修改自动优化字段，只显示"开启"选项 -->
        <a-form-item label="自动优化" name="autoOptimize">
          <a-radio-group v-model:value="formState.autoOptimize">
            <a-radio-button :value="true">开启</a-radio-button>
          </a-radio-group>
        </a-form-item>

        <!-- 由于自动优化始终开启，投放场景始终显示 -->
        <a-form-item label="投放场景" name="scenario">
          <a-radio-group v-model:value="formState.scenario">
            <a-radio-button :value="0">日常投放</a-radio-button>
            <a-radio-button :value="1">增量投放</a-radio-button>
          </a-radio-group>
        </a-form-item>

        <a-form-item label="投放时间">
          <a-date-picker
            v-model:value="startDate"
            format="YYYY-MM-DD"
            style="width: 200px"
            :disabledDate="disabledStartDate"
            @change="(date: dayjs.Dayjs | null, dateString: string) => (formState.startDate = dateString)"
          />
          <a-form-item-rest>
            <span style="margin: 0 8px">至</span>
            <a-date-picker
              v-model:value="endDate"
              format="YYYY-MM-DD"
              style="width: 200px"
              :disabledDate="disabledEndDate"
              :disabled="formState.endDate === '9999-12-31'"
              @change="(date: dayjs.Dayjs | null, dateString: string) => (formState.endDate = dateString)"
            />
            <a-checkbox :checked="formState.endDate === '9999-12-31'" style="margin-left: 12px" @change="handleLongTermChange">
              长期投放
            </a-checkbox>
          </a-form-item-rest>
        </a-form-item>

        <!-- 转化追踪字段 -->
        <a-form-item label="转化追踪" name="conversionTracking">
          <div style="display: flex; align-items: center">
            <span v-if="selectedConversions.length > 0" style="margin-right: 12px">
              已选择: {{ selectedConversions.length }}个转化追踪
            </span>
            <a-button type="primary" @click="openSelectConversionModal"> 选择转化追踪 </a-button>
          </div>
        </a-form-item>

        <!-- 简化的已选转化追踪展示区域 -->
        <a-form-item v-if="selectedConversions.length > 0" label="已选转化追踪">
          <div class="selected-conversions-simple">
            <div class="account-group" v-for="account in accountsWithConversions" :key="account._id">
              <div class="account-header">
                <span class="account-name">{{ account.Name }}</span>
                <span class="account-count">{{ getAccountConversionCount(account._id) }}个转化追踪</span>
              </div>
              <div class="conversion-chips">
                <a-tag
                  v-for="conversion in getAccountConversions(account._id)"
                  :key="conversion.conversionId || conversion.id"
                  closable
                  @close="removeConversion(conversion.conversionId || conversion.id || 0)"
                  class="conversion-chip"
                >
                  {{ conversion.name || conversion.conversionName }}
                  ({{ conversion.type || `类型${conversion.conversionType}` }})
                  <span v-if="conversion.appId">[应用ID: {{ conversion.appId }}]</span>
                </a-tag>
              </div>
            </div>
          </div>
        </a-form-item>

        <!-- 出价方式字段 -->
        <a-form-item label="出价方式" name="bid_mode">
          <a-radio-group v-model:value="formState.bid_mode">
            <a-radio-button :value="1">统一设置</a-radio-button>
            <a-radio-button :value="2">多账户分别设置</a-radio-button>
          </a-radio-group>
        </a-form-item>

        <!-- 统一设置模式下的出价 -->
        <a-form-item v-if="formState.bid_mode === 1" label="出价" name="converBidMap">
          <CampaignBid v-model="formState.converBidMap" :minBid="3" :maxBid="100" :precision="0" />
        </a-form-item>

        <!-- 多账户分别设置模式下的出价 -->
        <a-form-item v-else label="出价" name="converBidMap">
          <div class="multi-account-bid-container">
            <a-button type="primary" @click="openSetConverBidModal"> 设置多账户出价 </a-button>
            <div v-if="hasSetMultiAccountBid" class="multi-account-bid-summary">
              已设置 {{ getConfiguredAccountCount() }} 个账户的出价
            </div>
          </div>
        </a-form-item>

        <!-- 开启状态字段 - 仅在新建计划时显示 -->
        <a-form-item label="开启状态" name="pause">
          <a-radio-group v-model:value="formState.pause">
            <a-radio-button :value="0">关闭</a-radio-button>
            <a-radio-button :value="1">开启</a-radio-button>
          </a-radio-group>
        </a-form-item>
      </template>
    </a-form>

    <!-- 使用选择广告计划组件 - 每次重新创建 -->
    <SelectedPlanModal
      v-if="showPlanModal"
      ref="selectedPlanModal"
      :selectedPlans="selectedPlans"
      :key="planModalKey"
      @select="handlePlanSelected"
    />

    <!-- 使用选择转化追踪组件 - 每次重新创建 -->
    <SelectedConversionModal
      v-if="showConversionModal"
      ref="selectedConversionModal"
      :selectedConversions="selectedConversions"
      :accountList="accountList"
      :key="conversionModalKey"
      @select="handleConversionSelected"
      @add-new="openAddConversionModal"
    />

    <!-- 使用新建转化追踪组件 -->
    <AddConversionModal ref="addConversionModalRef" :accountList="accountList" @success="handleAddConversionSuccess" />

    <!-- 使用 SetConverBid 组件 -->
    <SetConverBid ref="setConverBidModal" @update="handleMultiAccountBidSet" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed, onMounted } from "vue";
import dayjs from "dayjs";
import ButtonGroup from "@/components/ButtonGroup.vue";
import SelectedPlanModal from "./SelectedPlanModal.vue";
import SelectedConversionModal from "./SelectedConversionModal.vue";
import AddConversionModal from "./AddConversionModal.vue";
import SetConverBid from "./SetConverBid.vue";
import CampaignBid from "@/pages/NewBatchCreateAd/components/common/CampaignBid.vue";
import CampaignName from "@/pages/NewBatchCreateAd/components/common/CampaignName.vue";
import { batchCreateAdStore } from "@/pages/NewBatchCreateAd/store/batchCreateAdStore";
import { Plan, Conversion, FormStatePlan as FormState, Account } from "@/pages/NewBatchCreateAd/adx/xiaomi/enum";

const visible = ref(false);
const startDate = ref<dayjs.Dayjs | null>(null);
const endDate = ref<dayjs.Dayjs | null>(null);
const selectedPlanModal = ref();
const selectedConversionModal = ref();
const selectedPlans = ref<Plan[]>([]);
const selectedConversions = ref<Conversion[]>([]);
const viewingAccountId = ref<number | null>(null);
const viewingConversionAccountId = ref<number | null>(null);
// 控制是否显示计划选择弹窗
const showPlanModal = ref(false);
// 控制是否显示转化追踪选择弹窗
const showConversionModal = ref(false);
// 用于强制重新渲染组件的key
const planModalKey = ref(0);
const conversionModalKey = ref(0);

const formState = reactive<FormState>({
  distribute_mode: [1],
  add_mode: 1,
  campaignType: 1,
  trafficMode: 0,
  budget: "200",
  deliveryPolicy: 0,
  autoOptimize: true,
  scenario: 0,
  productType: 1,
  startDate: "",
  endDate: "",
  conversionTracking: 0,
  name: "",
  auto_suffix_id: false,
  pause: 1,
  bid_mode: 1,
  converBidMap: {
    type: "NORMAL_BID",
    value: 3,
  },
  rule_distribute_mode: 0,
});

const rules = {
  distribute_mode: [{ required: true, message: "请选择多账号分配方式" }],
  add_mode: [{ required: true, message: "请选择创建方式" }],
  campaignType: [{ required: true, message: "请选择投放范围" }],
  budget: [{ required: true, message: "请输入预算" }],
  // 仅在新建计划时验证计划名称
  name: [
    {
      required: true,
      message: "",
      // 仅在新建计划时验证，且在失去焦点时触发
      validator: (rule: any, value: string) => {
        // 只在提交时验证或用户手动触发验证时生效
        if (formState.add_mode === 1 && !value) {
          return Promise.reject("");
        }
        return Promise.resolve();
      },
      trigger: 'blur' // 只在失去焦点时触发验证
    },
  ],
};

const formRef = ref();

// 禁用今天之前的日期
const disabledStartDate = (current: dayjs.Dayjs | null) => {
  return current && current < dayjs().startOf("day");
};

// 禁用开始日期之前的日期
const disabledEndDate = (current: dayjs.Dayjs | null) => {
  return current && (current < dayjs().startOf("day") || (startDate.value && current < dayjs(startDate.value).startOf("day")));
};

const handleLongTermChange = (e: { target: { checked: boolean } }) => {
  if (e.target.checked) {
    // 如果选择长期投放，设置结束日期为无限远
    formState.endDate = "9999-12-31";
    endDate.value = null;
  } else {
    // 如果取消长期投放，设置默认结束日期为30天后
    const defaultEndDate = dayjs(startDate.value).add(30, "day");
    endDate.value = defaultEndDate;
    formState.endDate = defaultEndDate.format("YYYY-MM-DD");
  }
};

// 使用 store 中的账号列表
const store = batchCreateAdStore();
// 初始化为空数组，完全依赖 store 提供的账号列表
const accountList = ref<Account[]>([]);

// 在组件挂载时从 store 获取账号列表
onMounted(() => {
  if (store.AccountItems && store.AccountItems.length > 0) {
    accountList.value = store.AccountItems;
  }
});

// 监听账号列表变化
watch(
  () => accountList.value,
  (newAccounts, oldAccounts) => {
    if (!newAccounts || !oldAccounts) return;

    // 如果账号数量减少，需要清理已选计划中不存在账号的计划
    const newAccountIds = new Set(newAccounts.map((acc) => acc._id));

    // 过滤掉不存在账号的计划
    selectedPlans.value = selectedPlans.value.filter((plan) => {
      const accountId = Math.floor(plan.id / 100);
      return newAccountIds.has(accountId);
    });

    // 更新当前查看的账号
    if (viewingAccountId.value && !newAccountIds.has(viewingAccountId.value)) {
      // 如果当前查看的账号已被移除，重置为第一个有计划的账号
      const accountWithPlans = newAccounts.find((account) => getAccountSelectedCount(account._id) > 0);

      if (accountWithPlans) {
        viewingAccountId.value = accountWithPlans._id;
      } else {
        viewingAccountId.value = null;
      }
    }

    // 同步更新弹窗中的已选计划
    if (selectedPlanModal.value && selectedPlanModal.value.updateSelectedPlans) {
      selectedPlanModal.value.updateSelectedPlans(selectedPlans.value);
    }

    // 同步更新弹窗中的账号列表
    if (selectedPlanModal.value && selectedPlanModal.value.updateAccountList) {
      selectedPlanModal.value.updateAccountList(newAccounts);
    }
  },
  { deep: true }
);

const openSelectCampaignModal = () => {
  // 先隐藏组件，确保组件会被销毁
  showPlanModal.value = false;

  // 增加key值，强制重新渲染组件
  planModalKey.value++;

  // 短暂延迟后再显示组件，确保组件被完全销毁和重新创建
  setTimeout(() => {
    // 显示组件
    showPlanModal.value = true;

    // 等待组件加载完成后再操作
    setTimeout(() => {
      if (selectedPlanModal.value) {
        // 先更新已选计划，再显示弹窗
        selectedPlanModal.value.updateSelectedPlans(selectedPlans.value);
        selectedPlanModal.value.updateAccountList(accountList.value);
        selectedPlanModal.value.show();
      }
    }, 50); // 增加延迟时间，确保组件完全加载
  }, 0);
};

const accountsWithPlans = computed(() => {
  return accountList.value.filter((account) => getAccountSelectedCount(account._id) > 0);
});

const filteredSelectedPlans = computed(() => {
  if (!viewingAccountId.value) return [];
  return selectedPlans.value.filter((plan) => Math.floor(plan.id / 100) === viewingAccountId.value);
});

const getAccountSelectedCount = (accountId: number) => {
  return selectedPlans.value.filter((plan) => Math.floor(plan.id / 100) === accountId).length;
};

const handlePlanSelected = (plans: Plan[]) => {
  // 过滤掉重复的计划
  const planIds = new Set();
  selectedPlans.value = plans.filter((plan) => {
    if (planIds.has(plan.id)) {
      return false;
    }
    planIds.add(plan.id);
    return true;
  });

  // 其余代码保持不变...
};

const removePlan = (planId: number) => {
  // 从已选计划中移除
  selectedPlans.value = selectedPlans.value.filter((plan) => plan.id !== planId);

  // 更新当前查看的账号
  if (filteredSelectedPlans.value.length === 0) {
    const accountWithPlans = accountList.value.find((account) => getAccountSelectedCount(account._id) > 0);

    if (accountWithPlans) {
      viewingAccountId.value = accountWithPlans._id;
    } else {
      viewingAccountId.value = null;
    }
  }

  // 同步更新弹窗中的已选计划
  if (selectedPlanModal.value && selectedPlanModal.value.updateSelectedPlans) {
    selectedPlanModal.value.updateSelectedPlans(selectedPlans.value);
  }
};

// 初始化日期
watch(
  () => visible.value,
  (newVal) => {
    if (newVal) {
      // 当弹窗打开时，初始化日期
      const today = dayjs();
      startDate.value = today;
      formState.startDate = today.format("YYYY-MM-DD");

      // 判断是否为长期投放
      if (formState.endDate === "9999-12-31") {
        endDate.value = null;
      } else {
        const defaultEndDate = today.add(30, "day");
        endDate.value = defaultEndDate;
        formState.endDate = defaultEndDate.format("YYYY-MM-DD");
      }
    } else {
      // 重置表单
      formState.startDate = "";
      formState.endDate = "";
      startDate.value = null;
      endDate.value = null;
    }
  }
);

// 监听创建方式变化
watch(
  () => formState.add_mode,
  (newVal) => {
    if (newVal === 2) {
      // 如果选择了已有计划，重置选择的计划
      selectedPlans.value = [];
    } else {
      // 如果选择了新建计划，重置计划名称
      formState.name = "";
    }
  }
);

// 监听投放范围变化
watch(
  () => formState.campaignType,
  (newVal) => {
    // 当投放范围不是非商店或米盟时，重置投放方式为默认值
    if (newVal !== 2 && newVal !== 3) {
      formState.deliveryPolicy = 0;
    }
  }
);

// 获取指定账户的所有计划
const getAccountPlans = (accountId: number) => {
  return selectedPlans.value.filter((plan) => Math.floor(plan.id / 100) === accountId);
};

// 监听计划选择弹窗的关闭事件
watch(
  () => selectedPlanModal.value,
  (newVal) => {
    if (newVal) {
      // 监听弹窗关闭事件
      const originalHide = newVal.hide;
      newVal.hide = () => {
        originalHide();
        // 立即销毁组件
        showPlanModal.value = false;
      };
    }
  },
  { immediate: true }
);

// 计算属性：判断是否禁用已有计划选项
const isExistingPlanDisabled = computed(() => {
  // 当多账号分配包含"不同定向包"(值为2)时，禁用已有计划选项
  return formState.distribute_mode.includes(2);
});

// 处理多账号分配方式变化
const handleDistributeModeChange = (val: number[]) => {
  formState.distribute_mode = val;

  // 当选择了不同定向包时，强制设置为新建计划
  if (val.includes(2)) {
    formState.add_mode = 1;

    // 如果有已选计划，清空它们，但不显示提示信息
    if (selectedPlans.value.length > 0) {
      selectedPlans.value = [];
    }
  }
};

// 打开选择转化追踪弹窗
const openSelectConversionModal = () => {
  // 先隐藏组件，确保组件会被销毁
  showConversionModal.value = false;

  // 增加key值，强制重新渲染组件
  conversionModalKey.value++;

  // 短暂延迟后再显示组件，确保组件被完全销毁和重新创建
  setTimeout(() => {
    // 显示组件
    showConversionModal.value = true;

    // 等待组件加载完成后再操作
    setTimeout(() => {
      if (selectedConversionModal.value) {
        // 确保传递的数据中包含正确的 conversionId 和 customerId 字段
        const conversionsWithCorrectIds = selectedConversions.value.map((conversion) => {
          // 确保 conversionId 存在
          const conversionId = conversion.conversionId || conversion.id || 0;

          // 推算 customerId，确保它存在
          const customerId = conversion.customerId || Math.floor(conversionId / 100);

          return {
            ...conversion,
            // 确保这些关键字段都存在且值正确
            id: conversionId,
            conversionId: conversionId,
            customerId: customerId,
            conversionName: conversion.conversionName || conversion.name || "",
            name: conversion.name || conversion.conversionName || "",
            type: conversion.type || `类型${conversion.conversionType || 0}`,
          };
        });

        selectedConversionModal.value.updateSelectedConversions(conversionsWithCorrectIds);
        selectedConversionModal.value.updateAccountList(accountList.value);
        selectedConversionModal.value.show();
      }
    }, 50);
  }, 0);
};

// 处理转化追踪选择
const handleConversionSelected = (conversions: Conversion[]) => {
  // 统一字段格式，确保关键字段都存在
  selectedConversions.value = conversions.map((conversion) => {
    // 确保 conversionId 存在
    const conversionId = conversion.conversionId || conversion.id || 0;

    // 确保 customerId 存在
    const customerId = conversion.customerId || Math.floor(conversionId / 100);

    return {
      // 基础数据
      ...conversion,
      // 确保 id、conversionId 和 customerId 都是有效的数字
      id: conversionId,
      conversionId: conversionId,
      customerId: customerId,
      // 确保名称和类型字段存在
      name: conversion.name || conversion.conversionName || "",
      conversionName: conversion.conversionName || conversion.name || "",
      type: conversion.type || `类型${conversion.conversionType || 0}`,
    };
  });

  // 设置表单状态
  if (selectedConversions.value.length > 0) {
    formState.conversionTracking = 1;

    // 设置当前查看的账号为第一个有转化追踪的账号
    viewingConversionAccountId.value = selectedConversions.value[0].customerId || null;
  } else {
    viewingConversionAccountId.value = null;
    formState.conversionTracking = 0;
  }

  // 选择完成后隐藏弹窗组件
  showConversionModal.value = false;
};

// 获取指定账户的所有转化追踪 - 修改为使用 customerId
const getAccountConversions = (accountId: number) => {
  return selectedConversions.value.filter((conversion) => {
    // 直接使用 customerId 而不是计算 conversionId/100
    return conversion.customerId === accountId;
  });
};

// 获取指定账号已选转化追踪数量 - 修改为使用 customerId
const getAccountConversionCount = (accountId: number) => {
  return selectedConversions.value.filter((conversion) => {
    // 直接使用 customerId 而不是计算 conversionId/100
    return conversion.customerId === accountId;
  }).length;
};

// 移除转化追踪
const removeConversion = (conversionId: number) => {
  // 从已选转化追踪中移除 - 修改判断条件，同时检查id和conversionId
  selectedConversions.value = selectedConversions.value.filter((conversion) => {
    const id = conversion.id || 0;
    const cId = conversion.conversionId || 0;
    return id !== conversionId && cId !== conversionId;
  });

  // 更新当前查看的账号
  if (viewingConversionAccountId.value) {
    const accountConversions = getAccountConversions(viewingConversionAccountId.value);
    if (accountConversions.length === 0) {
      const accountWithConversions = accountList.value.find((account) => getAccountConversionCount(account._id) > 0);

      if (accountWithConversions) {
        viewingConversionAccountId.value = accountWithConversions._id;
      } else {
        viewingConversionAccountId.value = null;
      }
    }
  }

  // 同步更新弹窗中的已选转化追踪
  if (selectedConversionModal.value && selectedConversionModal.value.updateSelectedConversions) {
    selectedConversionModal.value.updateSelectedConversions(selectedConversions.value);
  }
};

// 计算有转化追踪的账号
const accountsWithConversions = computed(() => {
  return accountList.value.filter((account) => getAccountConversionCount(account._id) > 0);
});

// 监听转化追踪选择弹窗的关闭事件
watch(
  () => selectedConversionModal.value,
  (newVal) => {
    if (newVal) {
      // 监听弹窗关闭事件
      const originalHide = newVal.hide;
      newVal.hide = () => {
        originalHide();
        // 立即销毁组件
        showConversionModal.value = false;
      };
    }
  },
  { immediate: true }
);

// 新建转化追踪相关
const addConversionModalRef = ref();

// 打开新建转化追踪弹框
const openAddConversionModal = () => {
  if (addConversionModalRef.value) {
    addConversionModalRef.value.show();
  }
};

// 处理新建转化追踪成功
const handleAddConversionSuccess = (newConversion: Conversion) => {
  // 通知转化追踪选择弹窗刷新列表
  if (selectedConversionModal.value && selectedConversionModal.value.addNewConversion) {
    selectedConversionModal.value.addNewConversion(newConversion);
  }
};

// 标记是否已设置多账户出价
const hasSetMultiAccountBid = ref(false);

// 获取已配置出价的账户数量
const getConfiguredAccountCount = () => {
  if (!formState.converBidMap) return 0;

  // 过滤掉 unified 键，只计算账户ID
  return Object.keys(formState.converBidMap).filter((key) => key !== "unified").length;
};

// 在组件引用部分添加
const setConverBidModal = ref();

// 修改打开设置多账户出价弹框的方法
const openSetConverBidModal = () => {
  if (setConverBidModal.value) {
    setConverBidModal.value.show(formState.converBidMap, accountList.value);
  }
};

// 添加处理多账户出价设置完成的方法
const handleMultiAccountBidSet = (bidMap: any) => {
  formState.converBidMap = bidMap;
  hasSetMultiAccountBid.value = true;
};

// 监听出价方式变化
watch(
  () => formState.bid_mode,
  (newMode) => {
    if (newMode === 1) {
      // 切换到统一设置模式
      // 如果之前已经设置了统一配置，则使用它
      if (formState.converBidMap.unified) {
        const unifiedConfig = formState.converBidMap.unified;
        formState.converBidMap = unifiedConfig;
      } else {
        // 如果没有统一配置，则创建默认配置
        formState.converBidMap = {
          type: "NORMAL_BID",
          value: 66,
        };
      }
    } else {
      // 切换到多账户分别设置模式
      // 保存当前统一配置
      const currentConfig = { ...formState.converBidMap };

      // 初始化多账户配置
      const multiAccountConfig: Record<string, any> = {};
      multiAccountConfig.unified = currentConfig;

      formState.converBidMap = multiAccountConfig;
    }
  }
);

// 导出给父组件使用的方法
const getData = () => {
  return formState;
};

defineExpose({
  getData,
});
</script>

<style scoped lang="less">
.selected-plans-simple {
  max-height: 300px;
  overflow-y: auto;
  border: 1px solid #f0f0f0;
  border-radius: 4px;
  padding: 12px;
}

.account-group {
  margin-bottom: 16px;
}

.account-group:last-child {
  margin-bottom: 0;
}

.account-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.account-name {
  font-weight: bold;
  flex: 1;
}

.account-count {
  color: #999;
  font-size: 12px;
}

.plan-chips {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.plan-chip {
  margin-right: 0;
  padding: 4px 8px;
}

.selected-conversions-simple {
  max-height: 300px;
  overflow-y: auto;
  border: 1px solid #f0f0f0;
  border-radius: 4px;
  padding: 12px;
  margin-bottom: 16px;
}

.conversion-chips {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.conversion-chip {
  margin-right: 0;
  padding: 4px 8px;
}

.empty-conversions {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
  border: 1px solid #f0f0f0;
  border-radius: 4px;
  margin-bottom: 16px;
}

.dynamic-packet {
  background-color: #f0f0f0;
  padding: 5px 15px;
  margin-top: 10px;
}
.dynamic-packet span {
  cursor: pointer;
  color: #1890ff;
}

.bid-tabs {
  width: 100%;
}

.bid-input-container {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.range-separator {
  margin: 0 8px;
  color: #999;
}

.addon-text {
  margin-left: 8px;
  color: #999;
}

.bid-tip {
  color: #999;
  font-size: 12px;
}

.multi-account-bid-summary {
  margin-top: 8px;
  font-size: 14px;
  color: #1890ff;
}
</style>
